package com.smasher.component.fragment

import android.util.Log
import android.view.View
import android.view.ViewGroup
import com.smasher.component.api.ApiKotlin
import com.smasher.component.entity.BeanCustomer
import com.smasher.dialog.select.BaseSelectWithApiDialog
import com.smasher.dialog.select.delegate.DefaultQueryDelegate
import com.smasher.dialog.select.delegate.ElementShowDelegate

class TestApiDialog : BaseSelectWithApiDialog<BeanCustomer>() {

    val queryDelegate = object: DefaultQueryDelegate(){

    }

    /**
     * 获取对话框宽度
     * @return 宽度值，可用 MATCH_PARENT/WRAP_CONTENT 或具体像素值
     */
    override fun getWidth(): Int {
        return ViewGroup.LayoutParams.MATCH_PARENT
    }

    /**
     * 获取对话框高度
     * @return 高度值，可用 MATCH_PARENT/WRAP_CONTENT 或具体像素值
     */
    override fun getHeight(): Int {
        return ViewGroup.LayoutParams.MATCH_PARENT
    }

    /**
     * DiffUtil 项对比 - 判断是否为同一项
     * @param p0 旧数据项
     * @param p1 新数据项
     * @return true表示是同一项（通常比较唯一标识）
     */
    override fun areItemsTheSameTarget(
        p0: BeanCustomer,
        p1: BeanCustomer
    ): Boolean {
        return p0 == p1
    }

    /**
     * DiffUtil 内容对比 - 判断内容是否相同
     * @param p0 旧数据项
     * @param p1 新数据项
     * @return true表示内容相同（比较数据内容字段）
     */
    override fun areContentsTheSameTarget(
        p0: BeanCustomer,
        p1: BeanCustomer
    ): Boolean {
        return p0.id == p1.id
    }

    /**
     * 网络数据请求方法（协程作用域）
     * @return 请求结果数据列表
     */
    override suspend fun queryNet(key: String, nextPageNumber: Int): List<BeanCustomer> {
        try {
            val requestBody = queryDelegate.createParam(key, nextPageNumber)
            val result = try {
                Result.success(ApiKotlin().getCustomerList(requestBody))
            } catch (e: Exception) {
                Result.failure(e)
            }
            if (result.isSuccess) {
                val container = result.getOrNull()
                return container?.data ?: emptyList()
            } else {
                val exception = result.exceptionOrNull()
                Log.e(TAG, "queryNet: ${exception?.message}")
            }
        } catch (e: Exception) {
            Log.e(TAG, "queryNet: ${e.message}")
        }
        return emptyList()
    }

    /**
     * 创建展示代理
     * @return ElementShowDelegate
     */
    override fun createShowDelegate(): ElementShowDelegate<BeanCustomer> {
        return object : ElementShowDelegate<BeanCustomer>() {
            override fun showMainTitle(element: BeanCustomer): String {
                return element.customerName
            }

            override fun showSubTitle(element: BeanCustomer): String {
                return element.customerNo
            }

            override fun bindShowingView(element: BeanCustomer, view: View) {
            }
         }
    }

    override fun initData() {

    }

    override fun initView() {

    }
}